import * as crypto from 'crypto';
import { APPID, API_SECRET } from './constant';

/**
 * Gets the signature for the given appId and secret.
 * @param appId The appId used as a key for the signature
 * @param apiSecret The secret key used for the signature
 * @param ts The timestamp
 * @returns The generated signature
 */
export function getSignature(ts: number): string {
  try {
    const auth = md5(APPID + ts);
    return hmacSHA1Encrypt(auth, API_SECRET);
  } catch (error) {
    console.error('Error generating signature:', error);
    throw error;
  }
}

/**
 * HMAC SHA1 encryption
 * @param encryptText The text to be encrypted
 * @param encryptKey The encryption key
 * @returns The encrypted string
 */
function hmacSHA1Encrypt(encryptText: string, encryptKey: string): string {
  const hmac = crypto.createHmac('sha1', encryptKey);
  hmac.update(encryptText, 'utf8');
  return hmac.digest('base64');
}

/**
 * Generates MD5 hash of the given text
 * @param text The text to be hashed
 * @returns The MD5 hash of the text
 */
function md5(text: string): string {
  return crypto
    .createHash('md5')
    .update(text, 'utf8')
    .digest('hex');
}